package com.athuahua.spzx.service.impl;

import cn.hutool.core.util.StrUtil;
import com.athuahua.spzx.exception.CodeException;
import com.athuahua.spzx.dto.system.LoginDto;
import com.athuahua.spzx.dto.system.SysUserDto;
import com.athuahua.spzx.vo.system.LoginVo;
import com.athuahua.spzx.utils.ResultCodeEnum;
import com.athuahua.spzx.utils.BaseContext;
import com.athuahua.spzx.properties.JwtProperties;
import com.athuahua.spzx.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.athuahua.spzx.entity.SysUser;
import com.athuahua.spzx.service.SysUserService;
import com.athuahua.spzx.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author huahua
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2024-07-21 11:28:28
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public LoginVo login(LoginDto loginDto) {
        //1.1 校验验证码
        String captcha = loginDto.getCaptcha();
        String key = loginDto.getCodeKey();
        //1.2 获取存储在redis中的验证码
        String redisCode = redisTemplate.opsForValue().get(
                "user:validate" + key);
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
            throw new CodeException(ResultCodeEnum.VALIDATECODE_ERROR);
        }



        //2 查询表并校验登录，返回token
        String userName = loginDto.getUserName();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getName, userName);

        List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
        if (sysUsers.isEmpty()) {
            throw new CodeException(ResultCodeEnum.LOGIN_ERROR);
        }
        SysUser sysUser = sysUsers.get(0);
        if (!(DigestUtils.md5Hex(loginDto.getPassword())).equals(sysUser.getPassword())) {
            throw new CodeException(ResultCodeEnum.LOGIN_ERROR);
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userName", sysUser.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(), //key
                jwtProperties.getAdminTtl(), //过期时间
                claims);

        //1.3 删除验证码
        redisTemplate.delete("user:validate" + key);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    @Override
    public SysUser getUserInfo() {
        Long currentId = BaseContext.getCurrentId();
        SysUser sysUser = sysUserMapper.selectById(currentId);
        sysUser.setPassword(null);


        return sysUser;
    }

    @Override
    public void logout() {
    }

    @Override
    public IPage<SysUser> findByPage(int page, int size, SysUserDto sysUserDto) {
        IPage<SysUser> iPage = new Page<>(
                page,
                size
        );

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询 开始时间和结束时间
        queryWrapper.like(!sysUserDto.getKeyword().isEmpty(), SysUser::getName, sysUserDto.getKeyword())
                .gt(!sysUserDto.getCreateTimeBegin().isEmpty(), SysUser::getUpdateTime, sysUserDto.getCreateTimeBegin())
                .lt(!sysUserDto.getCreateTimeEnd().isEmpty(), SysUser::getUpdateTime, sysUserDto.getCreateTimeEnd())
                .orderByDesc(SysUser::getUpdateTime);

        return sysUserMapper.selectPage(iPage, queryWrapper);
    }
}




